/*************************************************************************
> File Name: recvfrom.c
> Author: hzy
> Created Time: 2023-09-19 10:34:05
> Description:服务器端
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    // 1、创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        exit(-1);
    }

    // 2、绑定固定端口和ip到套接字
    struct sockaddr_in bind_addr;
    bind_addr.sin_family = AF_INET;
    // 给当前程序绑定一个自己制定的固定端口
    bind_addr.sin_port = htons(10086);
    // 给当前程序绑定一个ip地址
    bind_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    // 3、绑定套接字
    int bind_ret = bind(sockfd,
                        (struct sockaddr *)&bind_addr,
                        sizeof(bind_addr));
    if (bind_ret != 0)
    {
        perror("bind");
        close(sockfd);
        exit(-1);
    }

    while (1)
    {
        // 4、接受消息
        char recv_buf[128] = {0};
        //定义接收方的结构体
        struct sockaddr_in recv_addr;
        //接收方结构体的大小
        socklen_t recv_len = sizeof(recv_addr);
        char ip_src[INET_ADDRSTRLEN] = {};

        int recv_ret = recvfrom(sockfd,
                                recv_buf,
                                sizeof(recv_buf),
                                0,
                                (struct sockaddr *)&recv_addr,
                                &recv_len);
        if (recv_ret < 0)
        {
            perror("recvfrom");
            break;
        }

        // 提取发送方地址
        printf("谁发送的消息\n");
        inet_ntop(AF_INET, &recv_addr.sin_addr.s_addr, ip_src, INET_ADDRSTRLEN);
        printf("ip: %s | port: %d\n", ip_src, ntohs(recv_addr.sin_port));
        printf("data(length=%ld):%s\n", strlen(recv_buf), recv_buf);
        printf("\n");

        //5、回显消息
        int send_ret = sendto(sockfd,
                              recv_buf,
                              strlen(recv_buf),
                              0,
                              (struct sockaddr *)&recv_addr,
                              sizeof(recv_addr));
    }

    close(sockfd);

    return 0;
}